package com.szcinda.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.controller.configuration.UserLoginToken;
import com.szcinda.repository.BaoGuanType;
import com.szcinda.service.dto.baoGuanType.BGTypeImportDto;
import com.szcinda.service.dto.baoGuanType.BGTypeService;
import com.szcinda.service.dto.baoGuanType.BgTypeExcelListener;
import com.szcinda.service.dto.baoGuanType.CreateBGTypeDto;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("bgType")
public class BGTypeController {

    private final BGTypeService bgTypeService;

    public BGTypeController(BGTypeService bgTypeService) {
        this.bgTypeService = bgTypeService;
    }


    @UserLoginToken
    @PostMapping("create")
    @OperationLogAnnotation(operDesc = "创建报关方式", operModel = "报关方式维护")
    public Result<String> create(@RequestBody CreateBGTypeDto createDto) {
        bgTypeService.create(createDto);
        return Result.success();
    }

    @GetMapping("delete/{id}/{userId}")
    @OperationLogAnnotation(operDesc = "删除报关方式", operModel = "报关方式维护")
    public Result<String> del(@PathVariable String id, @PathVariable String userId) {
        bgTypeService.delete(id, userId);
        return Result.success();
    }

    @UserLoginToken
    @GetMapping("all")
    public Result<List<BaoGuanType>> query() {
        return Result.success(bgTypeService.findAll());
    }


    @PostMapping("/import/{opId}")
    @OperationLogAnnotation(operDesc = "导入报关方式", operModel = "报关方式维护")
    public Result<String> orderImport(@RequestParam("file") MultipartFile file, @PathVariable String opId) throws Exception {
        InputStream inputStream = file.getInputStream();
        try {
            BgTypeExcelListener listener = new BgTypeExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, BGTypeImportDto.class), listener);
            bgTypeService.batchCreate(listener.getImportDatas(), opId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
